package com.ruoyi.exen.common.utils.OAPush;


import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.exen.common.domain.EcologyBizEc;
import com.ruoyi.exen.common.domain.ProcessPushDto;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


/**
 * 推送OA工具类
 */
public class OAPushUtil {

    public static final String APPID = "cgzb";

    private static final RestTemplate restTemplate = new RestTemplate();
    //OA域名
    private static final String getBaseUrl = "http://10.1.4.101";
    //获取token
    private static final String getTokenUrl = "http://10.1.4.101/api/ec/dev/auth/applytoken";
    //流程推送url
    private static final String processPushUrl = "http://10.1.4.101/api/workflow/paService/doCreateRequest";

    /**
     * 获取token
     *
     * @param ecologyBizEc 许可证信息
     * @return token
     */
    public static String getToken(EcologyBizEc ecologyBizEc) {

        // 公钥加密,所以RSA对象私钥为null
        RSA rsa = new RSA(null, ecologyBizEc.getServerPublicKey());
        //对秘钥进行加密
        String encryptSecret = rsa.encryptBase64(ecologyBizEc.getSecrit(), CharsetUtil.CHARSET_UTF_8,
                KeyType.PublicKey);
        // 创建请求头，添加appid和secret参数
        HttpHeaders headers = new HttpHeaders();
        headers.set("appid", ecologyBizEc.getAppid());
        headers.set("secret", encryptSecret);
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建请求实体，不需要请求体数据
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        // 发送POST请求，获取响应实体
        ResponseEntity<String> responseEntity = restTemplate.exchange(getTokenUrl, HttpMethod.POST, requestEntity,
                String.class);

        // 检查请求是否成功（状态码为2xx）
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            String response = responseEntity.getBody();
            // 处理响应，提取其中的token
            // 例如，如果响应是JSON格式：
            //JSONObject responseJson = new JSONObject(Integer.parseInt(response));
            JSONObject responseJson = JSON.parseObject(response);
            assert responseJson != null;
            String token = responseJson.getString("token");
            System.out.println("OAToken： " + token);
            return token;
        } else {
            // 请求失败
            return null;
        }
    }

    /**
     * 向OA推送流程
     *
     * @param processPushDto 推送数据
     * @param ecologyBizEc   许可证信息
     * @param token          token
     * @param userid         用户id-OA用户信息id-对应sys_user id字段
     * @return 响应
     */
    public static String processPush(ProcessPushDto processPushDto, EcologyBizEc ecologyBizEc, String token,
                                     String userid) {

        //封装请求头参数
        RSA rsa = new RSA(null, ecologyBizEc.getServerPublicKey());
        //对用户信息进行加密传输,暂仅支持传输OA用户ID
        String encryptUserid = rsa.encryptBase64(userid, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        //设置Content-Type为application/x-www-form-urlencoded
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("appid", ecologyBizEc.getAppid());
        headers.set("token", token);
        headers.set("userid", encryptUserid);

        // 构建请求体
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

        map.add("detailData", JSONObject.toJSONString(processPushDto.getDetailData()));
        map.add("mainData", JSONObject.toJSONString(processPushDto.getMainData().getMainDataTableFields()));
        map.add("otherParams", JSONObject.toJSONString(processPushDto.getOtherParams()));
        map.add("remark", processPushDto.getRemark());
        map.add("requestLevel", processPushDto.getRequestLevel());
        map.add("requestName", processPushDto.getRequestName());
        map.add("workflowId", String.valueOf(processPushDto.getWorkflowId()));

        // 创建 HTTP 请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);

        // 发送POST请求，获取响应实体
        ResponseEntity<String> responseEntity = restTemplate.exchange(processPushUrl, HttpMethod.POST, requestEntity,
                String.class);

        // 获取响应体
        System.out.println(requestEntity.getBody());

        return responseEntity.getBody();
    }


    /**
     * 处理OA响应信息
     *
     * @param jsonString OA响应信息
     * @return code值
     */
    public static String getCodeValue(String jsonString) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(jsonString);
            return jsonNode.get("code").asText();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
